<template>
  <!-- v-pagePermissions="pagePermissions"  -->
  <div class="white-bg commonBoxmp">
    <el-scrollbar class="HeightAuto">
      <div class="">
        <el-button type="primary" @click="downDom">下载docx</el-button>
      </div>
      <div style="border: 1px solid #ccc; margin-top: 20px">
        <Toolbar
          style="border-bottom: 1px solid #ccc"
          :editor="editorRef"
          :defaultConfig="toolbarConfig"
          :mode="mode"
        />
        <Editor
          style="height: 500px; overflow-y: hidden"
          v-model="valueHtml"
          :defaultConfig="editorConfig"
          :mode="mode"
          @onCreated="handleCreated"
        />
      </div>
    </el-scrollbar>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, shallowRef, onMounted, onBeforeUnmount } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import {
  Document,
  Packer,
  Paragraph,
  TextRun,
  Table,
  TableCell,
  TableRow,
} from "docx";
import { saveAs } from "file-saver";
import * as htmlparser2 from "htmlparser2";
import { usehtmlJsonToDocJson } from "/@ts/components/docx/hooks/htmlJsonToDocJson";

/*
基本数据类型
引用数据类型（复杂类型） 个人建议 ref初始化变量 
ref 和 reactive 本质我们可以简单的理解为ref是对reactive的二次包装, 
ref定义的数据访问的时候要多一个.value
*/
const mode = ref("default");
const state = reactive({});
// 编辑器实例，必须用 shallowRef
const editorRef: any = shallowRef();

// 内容 HTML
const valueHtml = ref("<p>hello</p>");

// 模拟 ajax 异步获取内容
onMounted(() => {
  setTimeout(() => {
    valueHtml.value = "<p>模拟 Ajax 异步设置内容</p>";
  }, 1500);
});

const toolbarConfig = {
  server: "/api/upload-img",
  customUpload(file: File, insertFn: any) {
    console.log("customUpload", file);
    return new Promise((resolve) => {
      // Simulate async insert image
      setTimeout(() => {
        const src = `https://www.baidu.com/img/flexible/logo/pc/result@2.png?r=${Math.random()}`;
        insertFn(src, "baidu logo", src);
        resolve("ok");
      }, 500);
    });
  },
};
const editorConfig = {
  placeholder: "请输入内容...",
  MENU_CONF: {
    //配置上传图片
    uploadImage: {
      base64LimitSize: 900 * 1024,
      // customUpload: (file:any, insertFn:any)=>{
      //   console.log('file :>> ', file);
      // }
    },
  },
};
const handleCreated = (editor: String) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
  editorRef.value.customConfig.customUploadImg = function customUpload(
    file: File,
    insertFn: any,
  ) {
    // TS 语法
    // async customUpload(file, insertFn) {                   // JS 语法
    // file 即选中的文件
    console.log("file :>> ", file);
    // 自己实现上传，并得到图片 url alt href
    // 最后插入图片
    // insertFn(url, alt, href)
  };
};
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});
const downDom = () => {
  const dom: any = htmlparser2.parseDocument(valueHtml.value);
  console.log("downDom", dom.children);
  const data = usehtmlJsonToDocJson(dom.children);
  console.log("sectionsData", data);
  const table = new Table({
    rows: [
      new TableRow({
        children: [
          new TableCell({
            children: [new Paragraph("Hello")],
          }),
          new TableCell({
            children: [],
          }),
        ],
      }),
      new TableRow({
        children: [
          new TableCell({
            children: [],
          }),
          new TableCell({
            children: [new Paragraph("World")],
          }),
        ],
      }),
    ],
  });
  const doc = new Document({
    sections: [
      {
        properties: {},
        children: data,
      },
    ],
  });
  Packer.toBlob(doc).then((blob) => {
    console.log(blob);
    saveAs(blob, "example.docx");
    console.log("Document created successfully");
  });
};
</script>

<style scoped lang="scss"></style>
